<?php

namespace app\api\controller;

use app\common\model\Comment;
use app\common\model\Post as P;
use app\common\model\VoteResult;
use think\facade\Db;

class Post extends ApiBase
{
    // 不需要验证token的方法
    protected $middleware = [
        'app\api\middleware\Auth' => ['except' => ["list", "nearbyPost","classPostList", "detail","recommend","interestPost","followUserPost","joinTopicPost","search"]],
    ];

    //首页推荐帖子(根据圈子推荐)
    public function recommend(){
        $topicIds = Db::name("topic")->where("index_recommend",1)->column("id");

        $where[] = ["topic_id","in",$topicIds];
        $list = P::getList($where);
        return success($list);
    }

    //帖子列表
    public function list()
    {
        $disId = input("dis_id");
        $topicId = input("topic_id");

        $uid = input("uid");
        $order = input("order");
        $type = input("type");

        $where = [];

        if ($type) {
            $where["post.type"] = $type;
        }

        if ($disId) {
            $where["discuss_id"] = $disId;
        }

        if ($topicId) {
            $where["topic_id"] = $topicId;
        }

        if ($uid) {
            $where["post.uid"] = $uid;
        }

        if (!$order) {
            $order = "id desc";
        }

        $list = P::getList($where, $order);
        return success($list);
    }

    //附近帖子列表
    public function nearbyPost()
    {
        $lat1 = input("lat");
        $lng1 = input("lng");

        $list = P::withJoin(['userInfo' => ['username', 'avatar'], 'topicInfo'])->paginate(10)->each(function ($item) use ($lat1, $lng1) {
            $item["comment_count"] = Db::name("comment")->where("post_id", $item["id"])->count();
            $item["fabulous_count"] = Db::name("post_fabulous")->where("post_id", $item["id"])->count();

            if ($item["discuss_id"] > 0) {
                $item["discuss_title"] = Db::name("discuss")->where("id", $item["discuss_id"])->value("title");
            }
            $distance = $this->getDistance($lat1, $lng1, $item["latitude"], $item["longitude"]);
            $item["distance"] = round($distance, 1);
            return $item;
        });

        return success($list);
    }

    //根据经纬度获取距离
    function getDistance($lat1, $lng1, $lat2, $lng2)
    {

        // 将角度转为狐度
        $radLat1 = deg2rad($lat1); // deg2rad()函数将角度转换为弧度
        $radLat2 = deg2rad($lat2);
        $radLng1 = deg2rad($lng1);
        $radLng2 = deg2rad($lng2);

        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;

        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137;

        return $s;
    }

    public function myPost()
    {
        $uid = $this->uid;
        $where["post.uid"] = $uid;

        $list = P::getList($where);
        return success($list);
    }

    public function myCollectPost()
    {
        $uid = $this->uid;
        $postIds = Db::name("post_collection")->where("uid", $uid)->column("post_id");

        $where[] = ["post.id", "in", $postIds];
        $list = P::getList($where);
        return success($list);
    }

    //    关注用户的帖子
    public function followUserPost()
    {
        $uid = $this->uid;

        $followUids = Db::name("follow")->where("uid", $uid)->column("follow_uid");
        $where[] = array("post.uid", "in", $followUids);
        $list = P::getList($where);
        return success($list);
    }
    //    加入圈子的帖子
    public function joinTopicPost()
    {
        $uid = $this->uid;

        if($uid > 0){
            $topicIds = Db::name("user_topic")->where("uid", $uid)->column("topic_id");
            $where[] = array("topic_id", "in", $topicIds);
            $list = P::getList($where,"id desc",10,$this->uid);
        }else{
            $list = P::getList();
        }
        
        return success($list);
    }
    /**
     * [发布帖子]
     * @param $token
     * @return json
     */
    public function addPost()
    {

        $userStatus = Db::name("user")->where("uid", $this->uid)->value("status");

        if ($userStatus != 0) {
            return error("该用户已被禁用");
        }

        $type = input("type");
        $media = input("media");

        //如果为视频类型帖子时检测是否上传视频
        if ($type == 2 && count($media) == 0) {
            return error("请上传视频");
        }

        $data = input("post.");
        $data["uid"] = $this->uid;
        $data["create_time"] = time();
        $wechat = new Wechat();
        if (!$wechat->checkText($data["content"]) && $data["content"]) {
            return error("内容违规违法");
        }
        $res = P::create($data);
        if ($res) {
            return success(["id" => $res->id], "发布成功");
        }
        return error("发布失败");
    }

    /**
     * [后台马甲用户发布帖子]
     */
    public function vestPostAdd()
    {

        $data = input("post.");

        $res = P::create($data);
        if ($res) {
            return notice("发布成功");
        }
        return error("发布失败");
    }
    /**
     * 新建图文
     */
    public function articleAdd()
    {
        $data = input("post.");
        $data["uid"] = $this->uid;
        $data["type"] = 3;

        $res = P::create($data);
        if ($res) {
            return notice("创建成功");
        }
        return error("创建失败");
    }

    //图文列表
    public function articleList()
    {
        $list = Db::name("post")->where("type", 3)->paginate(10);
        return success($list);
    }

    //修改帖子
    public function editPost()
    {

        $data = input("post.");
        $data["uid"] = $this->uid;

        $res = P::update($data);
        if ($res) {
            return notice("修改成功");
        }
        return error("修改失败");
    }

    //取消置顶
    public function topPostDel(){
        $data = input("post.");
        $res = Db::name("topic_top")->where($data)->delete();
        if($res){
            return notice("已删除置顶");
        }

        return error("删除置顶失败");
    }
    //删除帖子
    public function del()
    {
        $id = input("id");
        $res = P::destroy($id);
        if ($res) {
            return notice("删除成功");
        }
        return error("删除失败");
    }

    //删除选择的帖子
    public function Changedel()
    {
        $id = input("id");
        $ids = explode($id, ",");
        $res = P::destroy($ids);
        if ($res) {
            return notice("删除成功");
        }
        return error("删除失败");
    }

    /**
     * [帖子详情]
     * @return [json]
     */
    public function detail()
    {

        $id = input("id");
        $uid = $this->uid;

        Db::name('post')->where('id', $id)->inc('read_count')->update();
        $postInfo = P::withJoin(["userInfo"])->where("id", $id)->find();

        $postInfo["is_follow"] = false;
        $postInfo["is_collection"] = false;
        $postInfo["is_thumb"] = false;

        $postInfo["topic_info"] = \app\common\model\Topic::find($postInfo["topic_id"]);

        $postInfo["topic_info"]["post_count"] = Db::name("post")->where("topic_id",$postInfo["topic_id"])->count();
        $postInfo["topic_info"]["user_count"] = Db::name("user_topic")->where("topic_id",$postInfo["topic_id"])->count();


        $isFollow = Db::name("follow")->where(["uid" => $uid, "follow_uid" => $postInfo["uid"]])->find();
        if ($isFollow) {
            $postInfo["is_follow"] = true;
        }

        $postInfo["comment_count"] = Db::name("comment")->where("post_id", $id)->count();
        $postInfo["collection_count"] = Db::name("post_collection")->where("post_id", $id)->count();

        $isCollection = Db::name("post_collection")->where(["uid" => $uid, "post_id" => $id])->find();

        if ($isCollection) {
            $postInfo["is_collection"] = true;
        }

        $isThumb = Db::name("post_fabulous")->where(["uid" => $uid, "post_id" => $id])->find();
        if ($isThumb) {
            $postInfo["is_thumb"] = true;
        }

        //投票
        if($postInfo["vote_id"] > 0){
            $vote = Db::name("vote_subject")->where("id",$postInfo["vote_id"])->find();
            $vote["options"] = Db::name("vote_option")->where("vote_id",$vote["id"])->select();
            $postInfo["vote_info"] = $vote;
            //投票结果
            $voteResult = VoteResult::where(["vote_id"=>$postInfo["vote_id"],"uid" => $this->uid])
                ->find();

            $postInfo["is_vote_result"] = false;
            if($voteResult){
                $postInfo["is_vote_result"] = true;
            }

        }

        return success($postInfo);
    }


    /**
     * 点赞帖子
     */
    public function addThumb()
    {
        $uid = $this->uid;
        $postId = input("id");
        $to_uid = Db::name("post")->where("id", $postId)->value("uid");
        $data["uid"] = $uid;
        $data["post_id"] = $postId;
        $isCollection = Db::name("post_fabulous")->where($data)->find();
        if ($isCollection) {
            return error("请勿重复点赞");
        }
        $res = Db::name("post_fabulous")->insert($data);

        if ($res) {
            $this->sendMsg($uid, $to_uid, $postId, 1, "点赞了您的帖子");

            return notice("点赞成功");
        }
        return error("点赞失败");
    }

    /**
     * 取消点赞帖子
     *
     */
    public function cancelThumb()
    {
        $uid = $this->uid;
        $postId = input("id");
        $where["uid"] = $uid;
        $where["post_id"] = $postId;

        $res = Db::name("post_fabulous")->where($where)->delete();

        if ($res) {
            return notice("已取消点赞");
        }
        return error("取消点赞失败");
    }

    public function addCollection()
    {
        $uid = $this->uid;
        $postId = input("id");
        $to_uid = input("uid");
        $data["uid"] = $uid;
        $data["post_id"] = $postId;
        $isCollection = $res = Db::name("post_collection")->where($data)->find();
        if ($isCollection) {
            return error("请勿重复收藏");
        }

        $res = Db::name("post_collection")->insert($data);

        if ($res) {
            $this->sendMsg($uid, $to_uid, $postId, 3, "收藏了您的贴子");
            return notice("收藏成功");
        }
        return error("收藏失败");
    }

    public function cancelCollection()
    {
        $uid = $this->uid;
        $postId = input("id");
        $where["uid"] = $uid;
        $where["post_id"] = $postId;
        $res = Db::name("post_collection")->where($where)->delete();

        if ($res) {
            return notice("已取消收藏");
        }
        return error("取消收藏失败");
    }

    //发表评论
    public function addComment()
    {

        $data = input("post.");
        $data["uid"] = $this->uid;

        $userStatus = Db::name("user")->where("uid", $this->uid)->value("status");

        if ($userStatus != 0) {
            return error("该用户已被禁用");
        }
        
        if ($this->checkText($data["content"]) != 0) {
            return error("内容违法违规");
        }

        $res = \app\common\model\Comment::create($data);

        if ($res) {
            $msgToUid = input("to_uid");

            if(empty($msgToUid)){
                $msgToUid = Db::name("post")->where("id",$data["post_id"])->value("uid");
            }

            $this->sendMsg($this->uid, $msgToUid, $data["post_id"], 2, "评论：" . $data["content"]);
            return success($res, "评论成功");
        }

        return error("评论失败");
    }
    //马甲用户发表评论
    public function vestCommentAdd()
    {
        $content = input("content");
        $postId = input("post_id");
        $to_uid = Db::name("post")->where("id", $postId)->value("uid");
        $uid = input("uid");

        $res = \app\common\model\Comment::create(["uid" => $uid, "post_id" => $postId, "content" => $content, "type" => 1, "create_tim" => time()]);

        if ($res) {
            $this->sendMsg($uid, $to_uid, $postId, 2, "评论：" . $content);
            return success($res, "评论成功");
        }

        return error("评论失败");
    }

    //马甲用户点赞
    public function vestFabulous()
    {
        $postId = input("id");
        $uids = input("uids");

        $data["post_id"] = $postId;

        $success = true;
        foreach ($uids as $uid) {
            $data["uid"] = $uid;
            $res = Db::name("post_fabulous")->insert($data);
            $to_uid = Db::name("post")->where("id", $postId)->value("uid");
            $this->sendMsg($uid, $to_uid, $postId, 1, "点赞了您的帖子");
            if (!$res) {
                $success = false;
            }
        }

        if ($success) {
            return notice("操作成功");
        }
        return error("发生错误");
    }

    //获取帖子二维码
    public function qrCode(){
        $id = input("id");
        $wechat = new Wechat();

        $qrCode = $wechat->makeQrCode("pages/post/detail",$id,"post_" .$id,"post");

        if($qrCode["success"]){
            return success($qrCode["src"]);

        }
        return  error($qrCode["msg"]);
    }

    //设置置顶帖子
    public function setTop(){
        $data = input("post.");
        $data['create_time'] = time();

        $res = Db::name("topic_top")->insert($data);
        if($res){
            return notice("置顶成功");
        }

        return error("置顶失败");

    }

    //发布投票
    public function voteAdd(){
        $data["uid"] = $this->uid;
        $data["topic_id"] = input("topic_id");
        $data["content"] = input("content");
        $data["address"] = input("address");
        $data["type"] = 4;

        $voteSubjectData["title"] = input("vote_title");
        $voteSubjectData["type"] = input("vote_type");
        $voteSubjectData["create_time"] = time();

        $expireTimeNum = input("expire_time");
        if($expireTimeNum === 1){
            $voteSubjectData["expire_time"] = time() + 86400;
        }

        if($expireTimeNum === 2){
            $voteSubjectData["expire_time"] = time() + 86400*7;
        }

        if($expireTimeNum === 3){
            $voteSubjectData["expire_time"] = time() + 86400*30;
        }

        if($expireTimeNum === 4){
            $voteSubjectData["expire_time"] = time() + 86400*90;
        }

        $voteSubjectId = Db::name("vote_subject")->insertGetId($voteSubjectData);

        if ($voteSubjectId){
            $voteOptionData["vote_id"] = $voteSubjectId;
            $voteOptions = input("vote_options");

            foreach ($voteOptions as $item){
                $voteOptionData["content"] = $item["value"];
                Db::name("vote_option")->insert($voteOptionData);
            }
            $data["vote_id"] = $voteSubjectId;
            $postAdd = P::create($data);
        }

        return success(["id" => $postAdd->id], "发布成功");
    }

    //圈子分类下帖子列表
    public function classPostList(){
        $classId = input("class_id");
        $topicIds = Db::name("topic")->where("cate_id",$classId)->column("id");

        $where[] = ["topic_id","in",$topicIds];
        $list = P::getList($where);
        
        return success($list);
    }

    //搜索帖子
    public function search(){
        $keyword = input("keyword");
        $where[] = ["content","like","%$keyword%"];
        $list = P::getList($where);
        return success($list);
    }
}
